package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.WmUserMapper;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.wemedia.dto.WmLoginDto;
import com.zhentao.model.wemedia.pojo.WmUser;
import com.zhentao.service.WmUserService;
import com.zhentao.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public ResponseResult login(WmLoginDto dto) {
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号或密码为空");
        }
        //查询账号是否存在
        WmUser wmUser = wmUserMapper.selectOne(new QueryWrapper<WmUser>().lambda()
                .eq(WmUser::getName, dto.getName()));
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号不存在");
        }
        //判断密码
        String salt = wmUser.getSalt();
        String pass = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes(StandardCharsets.UTF_8));
        if (!pass.equals(wmUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
        }
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        wmUser.setPassword(null);
        wmUser.setSalt(null);
        map.put("user", wmUser);
        return ResponseResult.okResult(map);
    }
}
